package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.redis.service.IStrategyStatisVORedisService;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.List;

/**
 * redis 缓存数据初始化监听器
 */
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
   @Autowired
   private IStrategyService strategyService;

   @Autowired
   private IStrategyStatisVORedisService strategyStatisVORedisService;


    //spring容器初始化成功之后执行逻辑
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("=======================");
        //1.查询MondoDB中所有攻略对象
        List<Strategy> list = strategyService.list();


        //2.遍历攻略对象集合,封装vo对象
        for (Strategy strategy : list) {
            //判断指定攻略id的vo对象是否存在
            if (strategyStatisVORedisService.isVoExists(strategy.getId())){
                continue;
            }

            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy, vo);
            vo.setStrategyId(strategy.getId());
            //3.将vo对象缓存到redis中
            strategyStatisVORedisService.setStrategyStatisVo(vo);
        }

        System.out.println("===============end===============");

    }
}
